package com.ugoodtech.mdcc.web.filter;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStream;

/**
 * User: stone
 * Date: 11-8-22
 * Time: 上午10:53
 */
public class VerificationCodeFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //ignore get request
        if (req.getMethod().equalsIgnoreCase("get")) {
            chain.doFilter(request, response);
            return;
        }
        //
        String inputCode = req.getParameter("verification");
        String verificationCode = (String) req.getSession(true).getAttribute("VerifyCode");
        if (verificationCode != null && verificationCode.equalsIgnoreCase(inputCode)) {
            //log.debug("verificationCode is correctly!");
            chain.doFilter(request, response);
        } else {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            JsonResponse jsonResponse = new JsonResponse();
            jsonResponse.setSuccess(false);
            jsonResponse.setErrorDescription("验证码错误");
            response.setContentType("text/html;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            mapper.writeValue(out, jsonResponse);

//            res.sendRedirect("/login.jsp?codeError=5");
        }
    }

    public void destroy() {

    }

    Log log = LogFactory.getLog(VerificationCodeFilter.class);
}
